import axios from 'axios'
import store from '@/store'
import messageCreate from '@/components/MessageCreate'
axios.defaults.baseURL = 'http://apis.imooc.com/api'
axios.defaults.timeout = 3000
axios.interceptors.request.use((config) => {
  store.commit('setError', { status: false })
  store.commit('setLoading', true)
  // token
  const token = store.state.token
  if (config.headers && token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  // 请求接口时统一加项目接口校验码
  config.params = { ...config.params, icode: '868BF406F5EE46BF' }
  if (config.data instanceof FormData) {
    config.data.append('icode', '868BF406F5EE46BF')
  } else {
    config.data = { ...config.data, icode: '868BF406F5EE46BF' }
  }
  return config
})
axios.interceptors.response.use(
  (response) => {
    store.commit('setLoading', false)
    // 数据返回处理
    if (response.status === 200 && response.data.code === 0) {
      return response.data
    } else {
      messageCreate({
        type: 'danger',
        message: response.data.data.msg
      })
      return response.data
    }
  },
  (error) => {
    const { error: message } = error.response.data
    store.commit('setError', { status: true, message })
    store.commit('setLoading', false)
    messageCreate({
      type: 'danger',
      message
    })
    return Promise.reject(error)
  }
)
export default axios
